#define NOMINMAX
#include "Timer.h"
#include <limits>

namespace SubPlayer
{
    Timer::Timer()
    {
        begin = GetTickCount64();
    }

    Timer::~Timer()
    {
        Clear();
    }

    ULONGLONG Timer::GetElapsedMilliseconds()
    {
        return GetTickCount64() - begin;
    }

    UINT_PTR Timer::AddTimer(ULONGLONG triggerMillisecond, TIMERPROC lpTimerFunc)
    {
        ULONGLONG timerTime = triggerMillisecond - GetElapsedMilliseconds();
        if (timerTime > 0 && timerTime <= std::numeric_limits<UINT>::max()) {
            activeTimers.push_back(SetTimer(NULL, 0, static_cast<UINT>(timerTime), lpTimerFunc));
            return NULL;
        }
        else {
            return NULL;
        }
    }

    void Timer::RemoveTimer(HWND hWnd, UINT_PTR timer)
    {
        KillTimer(hWnd, timer);
        vector<UINT_PTR>::iterator item = std::find(activeTimers.begin(), activeTimers.end(), timer);
        if (item != activeTimers.end()) {
            activeTimers.erase(item);
        }
    }

    void Timer::Reset()
    {
        begin = GetTickCount64();
        Clear();
    }

    void Timer::Clear()
    {
        for (vector<UINT_PTR>::iterator it = activeTimers.begin(); it != activeTimers.end(); it++) {
            KillTimer(NULL, *it);
        }
    }

}